package org.example.service;


import org.example.entity.MyUserDetails;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.context.SecurityContext;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;

import java.util.Collection;
import java.util.List;


// 自定义权限校验器
@Component("myValidator")
public class AuthorityValidator {

    public boolean checkAuthority(String authority){
        // 这个方法不行，因为获取的是List<SimpleGrantedAuthority> ,而不是 List<String>
//       return SecurityContextHolder.getContext().getAuthentication().getAuthorities().contains(authority);

        //获取用户信息
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        MyUserDetails userDetails = (MyUserDetails) authentication.getPrincipal();
        List<String> authorityList = userDetails.getAuthorityList();
        return authorityList.contains(authority);
    }

}
